package com.spikegpsongoogleappengine.datasource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.spikegpsongoogleappengine.CompanyInfo;

public class CompanyInfoHttpDataSource implements CompanyInfoDataSource {
	
	private static final String TAG = "HttpDataSource";
	
	/* (non-Javadoc)
	 * @see com.spikegpsongoogleappengine.datasource.CompanyInfoDataSource#getCompanies(java.lang.String, java.lang.Double, java.lang.Double)
	 */
	@Override
	public List<CompanyInfo> getCompanies(final String queryText, Double lat,
			Double lng) {
		try {
			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        // Create a new HttpClient and Post Header
	        HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost("http://sinisa229.appspot.com/dataProvider");
	        nameValuePairs.add(new BasicNameValuePair("q", "%"+queryText+"%"));
	        
	        nameValuePairs.add(new BasicNameValuePair("lat", lat.toString()));
			nameValuePairs.add(new BasicNameValuePair("lng", lng.toString()));

	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        HttpEntity entity = response.getEntity();
	        InputStream contentStream = entity.getContent();
	        StringBuilder builder = new StringBuilder();
	        
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(contentStream));
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
	        
	        String json = new String(builder.toString());//.replaceAll("@", "_").replaceAll("#", "_").replaceAll("&", "_").replaceAll("&", "_").replaceAll("\n", "");
	        return companyInfosToList(json);
	    } catch (ClientProtocolException e) {
	        Log.e(TAG, "Error while geting url", e);
	    } catch (IOException e) {
	    	Log.e(TAG, "Error while geting url", e);
	    }
		//TODO handle properly
		return new ArrayList<CompanyInfo>();
	}
	
	private List<CompanyInfo> companyInfosToList(String content) {
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		try {
			JSONArray array = new JSONArray(content);
			for (int i = 0; i < array.length(); i++) {
				CompanyInfo companyInfo = new CompanyInfo();
				JSONObject companyInfoJson = array.getJSONObject(i);
				Iterator keys = companyInfoJson.keys();
				List<String> keyList = new ArrayList<String>();
				while (keys.hasNext()) {
					keyList.add(keys.next().toString());
				}
				if (keyList.contains("fnorgurl"))
				companyInfo.setFnOrgUrl(companyInfoJson.getString("fnorgurl"));
				
				if (keyList.contains("latitude"))
				companyInfo.setLatitude(companyInfoJson.getDouble("latitude"));
				
				if (keyList.contains("locality"))
				companyInfo.setLocality(companyInfoJson.getString("locality"));
				
				if (keyList.contains("longitude"))
				companyInfo.setLongitude(companyInfoJson.getDouble("longitude"));
				
				if (keyList.contains("setorderrightcorner"))
				companyInfo.setOrderRightCorner(companyInfoJson.getString("setorderrightcorner"));
				
				if (keyList.contains("servicelinks"))
				companyInfo.setServiceLinks(companyInfoJson.getString("servicelinks"));
				
				if (keyList.contains("streetaddress"))
				companyInfo.setStreetAddress(companyInfoJson.getString("streetaddress"));
				
				if (keyList.contains("tel"))
				companyInfo.setTel(companyInfoJson.getString("tel"));
				
				if (keyList.contains("url"))
				companyInfo.setUrl(companyInfoJson.getString("url"));
				companyInfos.add(companyInfo);
			}
			return companyInfos;
		} catch (JSONException e) {
			Log.d(TAG, "Error while converting from string", e);
		}
		//TODO If exception happens communicate error to user
		return companyInfos;
	}

}
